import fs from "fs";
import path from "path";

export class CAUtils {
	static generate(caPath: string = ".") {
		const OPENSSL_BIN = process.env.OPENSSL_BIN || "openssl";
		const crtFileName = "rootCA.crt";
		const keyFileName = "rootCA.key";
		const crtFilePath = path.join(caPath, crtFileName);
		const keyFilePath = path.join(caPath, keyFileName);

		const opensslCommand = `${OPENSSL_BIN} req -x509 -newkey rsa:4096 -keyout ${keyFilePath} -out ${crtFilePath} -days 1024 -nodes -subj "/C=US/ST=CA/L=San Francisco/O=Hada Proxy/OU=Hada Proxy/CN=Hada Proxy Root CA"`;
		if (fs.existsSync(crtFilePath) && fs.existsSync(keyFilePath)) {
			return Promise.resolve({
				crtFilePath: crtFilePath,
				keyFilePath,
			});
		}

		return new Promise<{ crtFilePath: string; keyFilePath: string }>(
			(resolve, reject) => {
				const exec = require("child_process").exec;
				exec(
					opensslCommand,
					{ cwd: caPath },
					(error: { message: any }, stdout: any, stderr: any) => {
						if (error) {
							reject(error.message);
							return;
						}
						resolve({
							crtFilePath,
							keyFilePath,
						});
					}
				);
			}
		);
	}
}
